package com.wisnews.controller.sr;


import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.wisnews.pojo.Input;
import com.wisnews.pojo.Result;
import com.wisnews.pojo.sec.entity.Operator;
import com.wisnews.pojo.sr.entity.News;
import com.wisnews.pojo.sr.vo.NewsStatistics;
import com.wisnews.service.sec.Impl.NewsServiceImpl;
import com.wisnews.util.Constants;
import com.wisnews.util.DateUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.SecurityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Set;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author yuyd
 * @since 2020-12-25
 */
@RestController
@RequestMapping("/news")
@Slf4j
public class NewsController {

    @Autowired
    private NewsServiceImpl newsService;

    @Autowired
    private RedisTemplate redisTemplate;

    /**
     * @description: 获取新闻
     * @param:
     * @return:
     * @author yuyd
     * @date: 2021/2/2 21:44
     */
    @RequestMapping("getNewsInfo")
    public Result<IPage<News>> getNewsInfo(@RequestBody Input<News> newsInput) {
        IPage<News> newspages = newsService.getNewsInfo4Page(newsInput.getReq(),newsInput.toPage());
        return new Result<>(Constants.SYS_CODE.SUCCESS, Constants.SYS_CODE.SUCCESS_MESSAGE,newspages);
    }

    /**
     * @description: 通过新闻id，获取新闻
     * @param: new
     * @return:
     * @author yuyd
     * @date: 2021/5/2 21:44
     */
    @RequestMapping("byId/{newsid}")
    public Result<News> getNewsInfoById(@PathVariable("newsid") String newsid) {
        Result<News> newsResult;
        News newspage;
        if ("stochastic".equals(newsid)) {
            //随机获取一条数据
            return null;
        }
        if (StringUtils.isBlank(newsid)) {

            return  new Result<>(Constants.SYS_CODE.FAIL, Constants.SYS_CODE.FAIL_MESSAGE);
        }
        newspage = newsService.getById(newsid);
        newsResult = new Result<>(Constants.SYS_CODE.SUCCESS, Constants.SYS_CODE.SUCCESS_MESSAGE, newspage);
        return newsResult;
    }

    /**
     * @description: 禁用新闻
     * @param:
     * @return:
     * @author yuyd
     * @date: 2021/5/3 16:43
     */
    @RequestMapping("forbiddene")
    public Result bathForbiddeneNews(@RequestBody List<String> ids) {
        Result newsResult = new Result<>(Constants.SYS_CODE.SUCCESS,Constants.SYS_CODE.SUCCESS_MESSAGE);
        try {
            newsService.bathForbiddeneNews(ids);
            //禁用成功删除缓存
            deleteOldCache();
            return newsResult;
        }catch (Exception e){

            return new Result<>(Constants.SYS_CODE.FAIL,Constants.SYS_CODE.FAIL_MESSAGE);
        }
    }

    /**
     * @description: 启用禁止查看的新闻
     * @param: 新闻id
     * @return:
     * @author yuyd
     * @date: 2021/5/2 21:53
     */
    @RequestMapping("enable")
    public Result enableNews(@RequestBody List<String> ids) {
        Result newsResult = new Result<>(Constants.SYS_CODE.SUCCESS,Constants.SYS_CODE.SUCCESS_MESSAGE);
        try {
            newsService.enableNews(ids);
            return newsResult;
        }catch (Exception e) {

            return new Result<>(Constants.SYS_CODE.FAIL,Constants.SYS_CODE.FAIL_MESSAGE);
        }
    }

    /**
     * @description: 批量删除
     * @param:
     * @return:
     * @author yuyd
     * @date: 2021/5/2 22:15
     */
    @RequestMapping(value = "delete",method = RequestMethod.POST)
    public Result batchDeleteeNews(@RequestBody List<String> ids) throws Exception {
        Result<Object> newsResult = new Result<>(Constants.SYS_CODE.SUCCESS,Constants.SYS_CODE.SUCCESS_MESSAGE);
            boolean removeTag = newsService.removeByIds(ids);
            if (removeTag) {
                //删除成功更新缓存
                deleteOldCache();
                return newsResult;
            }else {
                return new Result<>(Constants.SYS_CODE.FAIL,Constants.SYS_CODE.FAIL_MESSAGE);
            }
    }

    /**
     * @description: 保存或更新新闻
     * @param: news
     * @return: result
     * @author yuyd
     * @date: 2021/5/2 21:54
     */
    @RequestMapping(value = "saveOrUpdateNews",method = RequestMethod.POST)
    public Result saveOrUpdateNews(@RequestBody News news) {

        news.setModificationTime(DateUtil.getLocalDateTime());
        //如果是用户新增的新闻
        if (StringUtils.isBlank(news.getNewsId())) {
            Operator user = (Operator)SecurityUtils.getSubject().getPrincipal();
            news.setNewsOperatorId(user.getOperatorId());
        }

        newsService.saveOrUpdate(news);
        return new Result(Constants.SYS_CODE.SUCCESS, Constants.SYS_CODE.SUCCESS_MESSAGE);
    }

    @RequestMapping(value = "getCountInfo",method = RequestMethod.POST)
    public Result getCountInfo() {
        List<NewsStatistics> newsStatistics = newsService.getNewsCountInfo();
        return new Result(Constants.SYS_CODE.SUCCESS, Constants.SYS_CODE.SUCCESS_MESSAGE,newsStatistics);
    }

    /**
     * @description: 获取当前登录用户编写的新闻
     * @param: input
     * @return:  result
     * @author yuyd
     * @date: 2021/5/2 21:56
     */
    @RequestMapping(value = "getCurrUserNews",method = RequestMethod.POST)
    public Result getCurrentLoginUserNews(Input input) {
        //获取当前登录用户信息
        Object principal = SecurityUtils.getSubject().getPrincipal();
        if (principal == null || !(principal instanceof Operator)) {
           return new Result<>(Constants.SYS_CODE.FAIL, Constants.SYS_CODE.FAIL,"获取登录用户信息失败！请重试！");
        }

        Operator operator = (Operator) principal;
        String operatorId = operator.getOperatorId();
        //获取新闻列表
        IPage<News> newsList = newsService.getNewsListByOperatorId(input.toPage(),operatorId);
        if (newsList == null) {
            return new Result(Constants.SYS_CODE.FAIL,Constants.SYS_CODE.FAIL);
        }
        return new Result(Constants.SYS_CODE.SUCCESS,Constants.SYS_CODE.SUCCESS,newsList);
    }

    /**
     * @description: 删除老缓存
     * @param:
     * @return:
     * @author yuyd
     * @date: 2021/5/18 10:09
     */
    private void deleteOldCache() throws Exception{
        //删除user::开头的reids缓存
        Set keys = redisTemplate.keys("news::*");
        redisTemplate.delete(keys);
    }


}
